package vip.ola.pay.channel.unizfb;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.abc.AbcPayController;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchPay;
import vip.ola.pay.service.RpcCommonService;

import java.util.Map;

import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_SUCCESS;

/**
 * 联通话费支付
 */
@Controller
@RequestMapping("/api/unizfb")
public class UnizfbPayController extends BaseController {

    private static final MyLog _log = MyLog.getLog(AbcPayController.class);

    @Autowired
    private RpcCommonService rpcCommonService;
    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    @RequestMapping("/notify")
    @ResponseBody
    public String notify(@RequestParam Map<String,Object> map){
        _log.info("接收unicom回调：" + map.toString());
        String payOrderId = map.get("id").toString();
        //PayOrder payOrder = rpcCommonService.rpcPayOrderService.findByMchOrderNo(mchOrderNo);
        PayOrder payOrder = rpcCommonService.rpcPayOrderService.findByPayOrderId(payOrderId);
        Long amount = payOrder.getAmount() / 100;
        Long a = Long.valueOf(map.get("money").toString());
        if(amount.longValue() != a){
            return "amount fail";
        }
        if(payOrder == null){
            return "order not exist!";
        }
        if (payOrder.getStatus() == PAY_STATUS_SUCCESS || payOrder.getStatus() == PAY_STATUS_COMPLETE) {
            return "ok";
        }
        PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        String retSign = map.get("sign").toString();
        if (retSign.equals(UnizfbPaymentService.getSignByNotify(map.get("uid").toString(),map.get("id").toString(),map.get("state").toString(),payPassageAccount.getPrivateKey()))){
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Success(payOrder.getPayOrderId());
            _log.info("更新订单状态为支付成功: result={}", result);
            if(result == 1){
                // 通知业务系统
                baseNotify4MchPay.doNotify(payOrder, true);
                return "ok";
            }
        }
        return "fail!";
    }
}
